package la.bbs558.scheduled;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import la.bbs558.common.Constants;
import la.bbs558.entity.UserData;
import la.bbs558.entity.UserVisitRetention;
import la.bbs558.service.UserDataService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;

/**
 * @author: Shanks
 * @date: 2024/1/18 14:48
 * @desc:
 */
@Component
@Slf4j
public class ScheduledManager {

    @Resource
    private UserDataService userDataService;
    @SneakyThrows
    @Scheduled(cron = "0 0 0 * * ?")
    public void syncVisitRetention(){
        log.info("开始同步留存数据");
        UserVisitRetention retention = new UserVisitRetention();
        for (int day : Constants.DAYS) {
            Field field = retention.getClass().getDeclaredField("count" + day);
            field.setAccessible(true);
            int size = userDataService.lambdaQuery()
                    .ge(UserData::getContinuousLoginDays, day)
                    .list().size();
            field.set(retention,size);
        }
        retention.setCreateDate(DateUtil.date().toString(Constants.YYYY_MM_DD));
        retention.insertOrUpdate();
        log.info("完成同步留存数据：" + JSON.toJSONString(retention));
    }
}
